package com.xuyu.common.tool.transaction;


import com.xuyu.common.tool.util.Tuple2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.function.Function;

/**
 * 用来处理spring下手动开启事务，简化开发的通用处理类
 * 无状态
 */
@Slf4j
public class SpringTransactionTool {

    private DataSourceTransactionManager transactionManager;


    /**
     * 执行事务逻辑
     * @param transactionDefinition 事务定义，传null的话使用默认的
     * @param function 执行的业务逻辑
     * @param param 参数
     * @return 返回结果 true为成功 返回结果       false为失败回滚了  返回异常
     */
    public Tuple2<Boolean, Object> doTransactionalOperation(TransactionDefinition transactionDefinition, Function<Object, Object> function, Object param) {
        // 开始事务
        TransactionDefinition txDef;
        if (transactionDefinition == null) {
            txDef = new DefaultTransactionDefinition();
        } else {
            txDef = new DefaultTransactionDefinition(transactionDefinition);
        }
        TransactionStatus txStatus = transactionManager.getTransaction(txDef);
        try {
            Object res = function.apply(param);
            // 提交事务
            transactionManager.commit(txStatus);
            return new Tuple2<>(Boolean.TRUE, res);
        } catch (Exception e) {
            // 回滚事务
            log.error("当前事务异常回滚!", e);
            transactionManager.rollback(txStatus);
            return new Tuple2<>(Boolean.FALSE, e);
        }
    }

}
